import os, sys, pygame, pygame.font
from pygame.color import THECOLORS
from visual import *
from pygame.locals import *
from random import *
import coords
import fileinput
from Ships.Miner import *
from Ships.Battleship import *
import EnvironmentSprites
import PathFinding.Map
import PathFinding.AStar
#http://www.pygame.org/wiki/SimpleFontManager?parent=CookBook

class cFontManager:
    '''
    A simple class used to manage Font objects and provide a simple way to use
    them to draw text on any surface.
 
    Directly import this file to use the class, or run this file from the
    command line to see a trivial sample.

    Written by Scott O. Nelson  
    '''
    def __init__(self, listOfFontNamesAndSizesAsTuple):
        '''
        Pass in a tuple of 2-item tuples.  Each 2-item tuple is a fontname / 
        size pair. To use the default font, pass in a None for the font name.
        Font objects are created for each of the pairs and can then be used
        to draw text with the Draw() method below.
        
        Ex: fontMgr = cFontManager(((None, 24), ('arial', 18), ('arial', 24),
            ('courier', 12), ('papyrus', 50)))
 
        TODO: add support for bold & italics
        '''
        
        self._fontDict = {}
        for pair in listOfFontNamesAndSizesAsTuple:
            assert len(pair) == 2, \
                "Pair must be composed of a font name and a size - ('arial', 24)"
            if pair[0]:
                fontFullFileName = pygame.font.match_font(pair[0])
            else:
                fontFullFileName = None # use default font
            self._fontDict[pair] = pygame.font.Font(fontFullFileName, pair[1])
 
    def Draw(self, surface, fontName, size, text, rectOrPosToDrawTo, color,
            alignHoriz='left', alignVert='top', antialias=False):
        '''
        Draw text with the given parameters on the given surface.
        
        surface - Surface to draw the text onto.
        
        fontName - Font name that identifies what font to use to draw the text.
        This font name must have been specified in the cFontManager 
        
        rectOrPosToDrawTo - Where to render the text at.  This can be a 2
        item tuple or a Rect.  If a position tuple is used, the align
        arguments will be ignored.
        
        color - Color to draw the text with.
        
        alignHoriz - Specifies horizontal alignment of the text in the
        rectOrPosToDrawTo Rect.  If rectOrPosToDrawTo is not a Rect, the
        alignment is ignored.
        
        alignVert - Specifies vertical alignment of the text in the
        rectOrPosToDrawTo Rect.  If rectOrPosToDrawTo is not a Rect, the
        alignment is ignored.
 
        antialias - Whether to draw the text anti-aliased or not.
        '''
        pair = (fontName, size)
        assert self._fontDict.has_key(pair), \
            'Font: %s Size: %d is not available in cFontManager.' % pair
        fontSurface = self._fontDict[(fontName, size)].render(text,
            antialias, color)
        if isinstance(rectOrPosToDrawTo, tuple):
            surface.blit(fontSurface, rectOrPosToDrawTo)
        elif isinstance(rectOrPosToDrawTo, pygame.Rect):
            fontRect = fontSurface.get_rect()
            # align horiz
            if alignHoriz == 'center':
                fontRect.centerx = rectOrPosToDrawTo.centerx
            elif alignHoriz == 'right':
                fontRect.right = rectOrPosToDrawTo.right
            else:
                fontRect.x = rectOrPosToDrawTo.x  # left
            # align vert
            if alignVert == 'center':
                fontRect.centery = rectOrPosToDrawTo.centery
            elif alignVert == 'bottom':
                fontRect.bottom = rectOrPosToDrawTo.bottom
            else:
                fontRect.y = rectOrPosToDrawTo.y  # top
                
            surface.blit(fontSurface, fontRect)

"""
# Define a function to erase old sprite positions
# This will be used later
def eraseSprite(screen, rect):
   screen.blit(blank, rect)
     

# Define a function to erase old sprite positions
# This will be used later
def eraseSprite(screen, rect):
   screen.blit(blank, rect)

# Define a function to erase old sprite positions
# This will be used later
def eraseSprite(screen, rect):
   screen.blit(blank, rect)"""


pygame.init()

def initGame(screen):

    background = pygame.Surface (screen.get_size())
    background = background.convert() 
    background = pygame.image.load("Open.jpg")

    pygame.display.flip()

    start = False
    while start != True:
        font = pygame.font.Font(None, 36)
        text = font.render("PRESS ANY KEY TO BEGIN", 1, (255, 255, 255))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery + 200      
        background.blit(text, textpos)
        screen.blit(background, (0, 0))
        pygame.display.flip()
        for event in pygame.event.get():
           if (event.type == KEYUP) or (event.type == KEYDOWN):
              start = True
        #pygame.font.Font.render('Press Any Key To Begin', background=None)
        
    
    return background

    #while pygame.event.get() == None:
        #Font.render('Press Any Key To Begin', background=None)

def initGrid(screen):
    
    background = pygame.Surface (screen.get_size())
    background = background.convert() 
    background = pygame.image.load("title.jpg")
    
    gridCount = 0 
    topGrid = 44
    
    green = (0,200,0)
    red = (255,0,0)
    blue = (0,0,255)
    
    fontMgr = cFontManager(((None, 24), (None, 48), (None, 36), (None,20), ('arial', 24)))
    fontMgr.Draw(background, None, 36, 'RESOURCES', (635,150), blue)
    
    #Bship = BattleShip((topGrid+2), (topGrid+2))
    #spritegroup = pygame.sprite.Group()
    #spritegroup.add(Bship)
    #spritegroup.draw(background)
    
    while (gridCount <= 32):
        pygame.draw.line (background, green, (topGrid,(topGrid + (16*gridCount))), (556,(topGrid + (16*gridCount))), 1)
        pygame.draw.line (background, green, ((topGrid + (16*gridCount)),topGrid), ((topGrid + (16*gridCount)),556), 1)
        
        if gridCount != 0: 
            fontMgr.Draw(background, None, 20, str(gridCount), (((topGrid - 14) + (16*gridCount)), 22), green)
            fontMgr.Draw(background, None, 20, str(gridCount), (22,((topGrid - 16) + (16*gridCount))), green)   
        
        #print gridCount
        gridCount += 1

    #battleshipSprite = pygame.image.load("battleship.gif")
    #battlerect = battleshipSprite.get_rect()    
    
    #screen.blit(battleshipSprite, battlerect)
    
    #pygame.draw.rect (background, (0,0,0,0), ballrect,0)
    #pygame.draw.line (background, (0,0,0), (44,44), (44,556), 1)
    #pygame.draw.line (background, (0,0,0), (44,44), (556,44), 1)
    
    return background

def showGrid (screen, grid):

    theMap = PathFinding.Map.Map()
    theMap.printAllCellCoords()
    

    spritegroupMinerals = pygame.sprite.Group()
    """i=0
    for i in range(theMap.mapSize):
        #self.map.append(self.mapCells[i].security)
        spritegroupMinerals.add(0)
        i+=1"""


    
    #infilename = raw_input( "Name of file to read from: " )
    #infile = open(infilename[:-1], "r" )
    infile = open( "Map.txt", "r" )
    Xcoord = 0
    Ycoord = 1
    offset = 13
    
    for i in range(1156):
        val = infile.read( 1 )
        Xcoord += 1
        print val
 
        if Xcoord == 33:
            Ycoord += 1
            Xcoord = 0
                 
        if val == 'P':
            print 'P'
        if val == 'B':
            print 'B'
        elif val == '1':
            Min = EnvironmentSprites.Mineral1((((Xcoord+1)*16)+offset),(((Ycoord+1)*16)+offset), theMap.getCell([Xcoord-1,Ycoord-1]))
            spritegroupMinerals.add(Min)
            #spritegroupMin1 = pygame.sprite.Group()
            #spritegroupMin1.add(Min)
            #spritegroupMin1.draw(grid)
            theMap.addResources(Xcoord-1, Ycoord-1, 10)
            print str(Xcoord-1)+","+str(Ycoord-1)
            #print 'min1'
        elif val == '2':
            Min = EnvironmentSprites.Mineral2((((Xcoord+1)*16)+offset),(((Ycoord+1)*16)+offset), theMap.getCell([Xcoord-1,Ycoord-1]))
            spritegroupMinerals.add(Min)
            #spritegroupMin2 = pygame.sprite.Group()
            #spritegroupMin2.add(Min)
            #spritegroupMin2.draw(grid)
            theMap.addResources(Xcoord-1, Ycoord-1, 20)
            print str(Xcoord-1)+","+str(Ycoord-1)            
        elif val == '3':
            Min = EnvironmentSprites.Mineral3((((Xcoord+1)*16)+offset),(((Ycoord+1)*16)+offset), theMap.getCell([Xcoord-1,Ycoord-1]))
            spritegroupMinerals.add(Min)
            #spritegroupMin3 = pygame.sprite.Group()
            #spritegroupMin3.add(Min)
            #spritegroupMin3.draw(grid)
            theMap.addResources(Xcoord-1, Ycoord-1, 30)
            print str(Xcoord-1)+","+str(Ycoord-1)            
        elif val == 'D':
            debris = EnvironmentSprites.Debris((((Xcoord+1)*16)+offset),(((Ycoord+1)*16)+offset))
            spritegroupMinerals.add(Min)
            spritegroupDebris = pygame.sprite.Group()
            spritegroupDebris.add(debris)
            spritegroupDebris.draw(grid)
            theMap.addObstacle(Xcoord-1, Ycoord-1)
            print str(Xcoord-1)+","+str(Ycoord-1)            
            #print 'min2'

    
    theMap.printAllCellCoords()
    theMap.updateInfluenceMap()
    #theMap.initialiseCells()
    
    #for line in infile:
    #    print line
    #    list = line.split( list )
      # Do stuff with line.
      # Remember that line is a string even if it looks like a number,
      # e.g. num = int( line )
      
    infile.close()
    
    Mineralx = uniform(44, 566)
    Mineraly = uniform(44, 566)

    #Bship = BattleShip(46, 46)
    miner = [Ships.Miner.MinerSprite([62,46], theMap, screen)]
    theMap.addMiner(miner[0])
    battleship = [Ships.Battleship.BattleShipSprite([62,46], theMap, screen)]
    theMap.addBattleShip(battleship[0])
 
    
    """Hello, i'm a highly visible comment"""
    #spritegroupCells = pygame.sprite.Group()
    spritegroupMiner = pygame.sprite.Group()
    spritegroupBattleShip = pygame.sprite.Group()
    
    #spritegroupCells.add(theMap.getCellSprites())
    spritegroupMiner.add(miner[0])
    spritegroupBattleShip.add(battleship[0])

    
    fontMgr = cFontManager(((None, 24), (None, 48), (None, 36), (None,20), ('arial', 24)))

    allsprites = pygame.sprite.RenderPlain(spritegroupMiner, spritegroupBattleShip, spritegroupMinerals)
    red = (255,0,0)
    
    quit = 0
    Xpos = 47
    Ypos = 47
    XposM = 62
    YposM = 47
    XposP = 47
    YposP = 62
    rescources = 100
    
    
    
        # (re)draw the game board (board) on the screen (ttt)
    running = 1
    
    screen.blit(grid,(0,0))

    
    pygame.display.flip() 
    #theMap.updateInfluenceMap()
    #theMap.printMap()
    
    while (running==1):

       for event in pygame.event.get():
        # event.type and event.key are ready for you to use
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.locals.K_m:
                    if theMap.mineralsMined >= 100:
                        theMap.mineralsMined -= 100
                        miner.append(Ships.Miner.MinerSprite([62,46], theMap, screen))
                        theMap.addMiner(miner[len(miner)-1])
                        spritegroupMiner.add(miner[len(miner)-1])
                    #spritegroup.draw(grid)
                        allsprites.add(spritegroupMiner)
                elif event.key == pygame.locals.K_b:
                    if theMap.mineralsMined >= 200:
                        theMap.mineralsMined -= 200
                        battleship.append(Ships.Battleship.BattleShipSprite([62,46], theMap, screen))
                        theMap.addBattleShip(battleship[len(battleship)-1])
                        spritegroupBattleShip.add(battleship[len(battleship)-1])
                        #spritegroup.draw(grid)
                        allsprites.add(spritegroupBattleShip)
                elif event.key == pygame.locals.K_ESCAPE:
                    running = 0  
       
       #updateEnvironment()
       i=0
       while i<800000: #eat up time
           i+=1
       
       fontMgr.Draw(grid, None, 36, str(rescources), (635,180), red)
        
       for aMiner in miner:
           aMiner.update()
       for aBattleShip in battleship:
           aBattleShip.update()


       """Updates and prints influence map"""
       theMap.updateInfluenceMap()
       #theMap.printMap()

       rescources += 50
       screen.blit(grid, (0, 0))
       allsprites.update()
       allsprites.draw(screen)
       pygame.display.flip()
    
         # update the display
    #return background


pygame.display.set_caption('Space Miner - The Galactic Quarry')

#pygame.mixer.music.load('Music/Imperial.mid')
#pygame.mixer.music.play()

    
size = width, height = 800, 600
speed = [2, 2]
black = 0, 0, 0



screen = pygame.display.set_mode(size)
initGame(screen)
grid = initGrid(screen)

showGrid(screen, grid)



##while 1:
##    for event in pygame.event.get():
##        if event.type == pygame.QUIT: sys.exit()
##
##        ballrect = ballrect.move(speed)
##    if ballrect.left < 0 or ballrect.right > width:
##        speed[0] = -speed[0]
##    if ballrect.top < 0 or ballrect.bottom > height:
##        speed[1] = -speed[1]
##
##    screen.fill(black)
##    screen.blit(ball, ballrect)
##    pygame.display.flip()

